package com.niuwa.p2p.interceptor;




import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.niuwa.p2p.action.JsonAction;
import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.entity.user.User;
import com.niuwa.p2p.exception.BusinessException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class JSONResultInterceptor extends AbstractInterceptor {

	/**
	 * @Fields: serialVersionUID
	 */
	private static final long serialVersionUID = 5036833959642477934L;

	private static Logger logger = Logger
			.getLogger(JSONResultInterceptor.class);

	private Class<JsonAction> jsonActionClass = JsonAction.class;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// 判断action是否为JsonAction的子类
		if (jsonActionClass.isAssignableFrom(invocation.getAction().getClass())) {
			JsonResult jsonResult = null;
			String actionResult = "none";
			JsonAction action = (JsonAction) invocation.getProxy().getAction();
			String actionName = invocation.getProxy().getActionName();
			String namespace = invocation.getProxy().getNamespace();
			
			/*
			 * 由于很多action虽然继承了JsonAction，但内部又有ajax的和非ajax的方法，所以这里拦截器要区分，ajax时始终返回JSON格式。
			 * 这里通过两种机制判断是否是ajax请求：（两种方法互补）
			 * 方式一：ajax请求中带上参数，is_ajax=true。（这里可以直接调用niwwa.ajax方法，里面统一封装处理的）
			 * 方式二：action.invoke()，判断有没有jsonResult对象，如果有也认为是ajax请求。
			 */
			HttpServletRequest httpreq=(HttpServletRequest)invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
			boolean isAjax=Boolean.valueOf(httpreq.getParameter("is_ajax"));
			
			//登录身份有效性验证
			User user=(User)ServletActionContext.getRequest().getSession().getAttribute("user");
			if(!"/user".equals(namespace) && user==null){//非登录  & session超时
				action.setResponse((HttpServletResponse)invocation.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE));
				action.writeToJSON(new JsonResult(false,true, action.getText("global.login.timeout"), "error","timeout"));
				return actionResult;
			}
			
			//执行action
			try {
				actionResult = invocation.invoke();// 调用action
				jsonResult = action.getResult();

				if ("index".equalsIgnoreCase(actionName)
						|| "addOrEdit".equalsIgnoreCase(actionName)
						|| "add".equalsIgnoreCase(actionName)
						|| "edit".equalsIgnoreCase(actionName)) {
					return actionResult;
				}
				if (jsonResult != null) {
					action.writeToJSON(jsonResult);// 将 JsonResult 转成json
				}
			} catch (BusinessException be) {
					// 处理业务错误,取得Message并返回
				    if(be.getArgs() != null && be.getArgs().length > 0){
				    	// 有参数的Message
				    	jsonResult = new JsonResult(false,
								StringUtils.defaultString(action.getText(be.getMessageId(), be.getArgs())));
				    } else {
				    	// 无参数的Message
						jsonResult = new JsonResult(false,
								StringUtils.defaultString(action.getText(be.getMessageId())));
				    }
				    if(be.getLogMessage()!=null){
				    	logger.error("execute Action Error!", be.getLogMessage());
				    }
					action.writeToJSON(jsonResult);
			} catch (Exception exception) {
				logger.error("execute Action Error!", exception);
				if(isAjax){
					action.writeToJSON(new JsonResult(false,true,action.getText("global.server.error"), "error","serverErr"));
					return "none";
				}
				throw exception;
			}

			return actionResult;
		} else {
			return invocation.invoke();
		}
	}

}
